
#include "app/config.h"
#include "app/window.h"
#include "core/pool.h"
#include "core/logs.h"

#include <windows.h>

struct VEWindow
{
	HWND handle;
};

VE_DEFINE_STATIC_POOL(VEWindow,VE_MAX_WINDOW_COUNT)

#define WINAPI_CALL( result ) \
	if( !(result) ) \
	{ \
		ve_log_error( "Failed call in %s, line %d, error %d", __FILE__, __LINE__, GetLastError() ); \
		goto error; \
	}

LRESULT CALLBACK ve_window_proc( HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam )
{
	switch( msg )
	{
	case WM_CLOSE:
		PostQuitMessage( 0 );
		return 0;
	}

	return DefWindowProc( wnd, msg, wparam, lparam );
}

VEWindow * ve_window_create( const char * name, int width, int height )
{
	const char * wnd_class_name = "VEngine";
	HINSTANCE instance;
	WNDCLASS wnd_class;
	VEWindow *result = ve_pool_alloc_VEWindow();

	WINAPI_CALL( instance = GetModuleHandle( 0 ) );

	memset( &wnd_class, 0, sizeof(wnd_class) );
	wnd_class.lpszClassName = wnd_class_name;
	wnd_class.lpfnWndProc = ve_window_proc;
	wnd_class.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
	wnd_class.hInstance = instance;
	wnd_class.hIcon = LoadIcon( 0, IDI_WINLOGO );
	wnd_class.hCursor = LoadCursor( 0, IDC_ARROW );
	WINAPI_CALL( RegisterClass( &wnd_class ) );

	WINAPI_CALL( result->handle = CreateWindow( wnd_class_name, name,
											   WS_OVERLAPPEDWINDOW | WS_VISIBLE,
											   CW_USEDEFAULT, CW_USEDEFAULT,
											   width, height,
											   0, 0, instance, 0 ) );

	return result;

error:
	ve_pool_free_VEWindow( result );
	return 0;
}

unsigned int ve_window_handle( VEWindow * window )
{
	return (unsigned int)window->handle;
}

void ve_window_delete( VEWindow *window )
{
	DestroyWindow( window->handle );
	ve_pool_free_VEWindow( window );
}
